<!DOCTYPE html>
<html>
<head>
    <title>玉石产品搜索</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link href="../static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="../static/bootstrap/icons/bootstrap-icons.css" rel="stylesheet">
    <style>
        .product-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .product-table th, .product-table td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
            font-size: 14px;
        }
        .product-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .product-table tr:hover {
            background-color: #f9f9f9;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .search-controls {
            margin: 20px 0;
            padding: 15px;
            background-color: #fffbf6;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .search-input {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-right: 10px;
            width: 200px;
        }
        .search-button {
            padding: 8px 16px;
            background-color: #c0a36c;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-button:hover {
            background-color: #a88c5a;
        }
        .product-card {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin: 10px 0;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .product-id {
            font-weight: bold;
            color: #c0a36c;
        }
        .product-name {
            font-size: 18px;
            margin: 5px 0;
        }
        .product-material {
            color: #666;
            font-size: 14px;
        }
        .product-details {
            margin-top: 10px;
            font-size: 12px;
            color: #888;
        }
        .product-left-column {
            width: 120px;
            float: left;
            margin-right: 15px;
        }
        .product-image {
            width: 120px;
            height: 160px;
            object-fit: cover;
            border-radius: 4px;
            display: block;
        }
        .product-content {
            overflow: hidden;
        }
        .product-card::after {
            content: "";
            display: table;
            clear: both;
        }
        
        /* 入库按钮样式 */
        .stock-btn {
            margin-top: 10px;
            padding: 6px 12px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            width: 100%;
            text-align: center;
        }
        .stock-btn:hover {
            background-color: #218838;
        }
        
        /* 响应式设计 - 移动设备优化 */
        @media (max-width: 768px) {
            .search-controls {
                padding: 10px;
            }
            
            .search-input {
                width: 100%;
                margin-right: 0;
                margin-bottom: 10px;
            }
            
            .search-button {
                width: 100%;
                margin-bottom: 10px;
            }
            
            /* 搜索方式选项在手机上垂直排列 */
            .search-options-container {
                flex-direction: column;
                gap: 8px;
            }
            
            .search-option-label {
                width: 100%;
                justify-content: flex-start;
            }
            
            /* 调整排序和类别选择器的宽度 */
            #categorySelect, #sortSelect {
                width: 100%;
            }
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 1200px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <h2 style="max-width: 1200px; margin: 0 auto 20px auto; padding: 0 20px;">玉石产品搜索</h2>

    <div class="search-controls">
        <div style="margin-bottom: 15px;">
            <label style="margin-right: 10px; font-weight: bold; display: block; margin-bottom: 8px;">搜索方式:</label>
            <div class="search-options-container" style="display: flex; flex-wrap: wrap; gap: 10px;">
                <label class="search-option-label" style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="colors" checked style="margin-right: 5px;"> 按颜色
                </label>
                <label class="search-option-label" style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="wu_xings" style="margin-right: 5px;"> 按五行
                </label>
                <label class="search-option-label" style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="major_material" style="margin-right: 5px;"> 按材质
                </label>
                <label class="search-option-label" style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="stock_id" style="margin-right: 5px;"> 按库存编号
                </label>
                <label class="search-option-label" style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="product_id" style="margin-right: 5px;"> 按产品ID
                </label>
                <label class="search-option-label" style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="buyer" style="margin-right: 5px;"> 按购买人
                </label>
            </div>
        </div>
        
        <!-- 按购买人搜索的特定UI -->
        <div id="buyerSearchPanel" style="display: none; margin-bottom: 15px;">
            <div style="display: flex; align-items: center; gap: 10px;">
                <input type="text" id="buyerNameInput" class="search-input" placeholder="输入购买人姓名..." style="width: 200px;">
                <button onclick="searchByBuyer()" class="search-button">查找</button>
            </div>
        </div>
        
        <div style="margin-bottom: 15px;">
            <label style="margin-right: 10px; font-weight: bold;">产品类别:</label>
            <select id="categorySelect" class="search-input" style="width: 150px;">
                <option value="all">全部</option>
            </select>
        </div>
        
        <div style="margin-bottom: 15px;">
            <label style="margin-right: 10px; font-weight: bold;">排序方式:</label>
            <select id="sortSelect" class="search-input" style="width: 180px;">
                <option value="designed_date_desc">设计时间降序 (最新在前)</option>
                <option value="designed_date_asc">设计时间升序 (最旧在前)</option>
            </select>
        </div>
        
        <input type="text" id="searchInput" class="search-input" placeholder="输入搜索关键词...">
        <button onclick="loadAllProducts()" class="search-button">显示全部</button>
        <div style="margin-top: 10px; font-size: 12px; color: #666;">
            提示：五行和颜色搜索支持多字符（如"火土"），将匹配包含火、土或火土的产品；产品ID搜索支持精确或部分匹配
        </div>
    </div>

    <div id="loading" class="loading">正在加载产品数据...</div>
    <div id="error" class="error" style="display: none;"></div>
    
    <div id="productContainer">
        <!-- 产品数据将在这里显示 -->
    </div>

    <script src="../static/js/common.js"></script>
    <!-- Bootstrap JS -->
    <script src="../static/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../static/js/ejj_functions.js"></script>
    <script>
        let allProducts = []; // 存储所有产品数据
        let jadeDir = ''; // 珠宝图片目录
        
        // 获取图片目录配置
        function getJadeConfig() {
            return fetch('/get_jade_config')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('无法获取配置');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.config && data.config.jade_dir) {
                        jadeDir = data.config.jade_dir.replace(/\\/g, '/');
                        return jadeDir;
                    } else {
                        throw new Error('配置中未找到jade_dir');
                    }
                });
        }
        
        // 获取产品图片URL
        function getProductImageUrl(productId) {
            if (!productId) return '/static/images/default_cover.jpg';
            
            // 使用后端图片服务
            return `/serve_jade_image?product_id=${productId}`;
        }
        
        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            // 页面加载时立即检查登录状态
            checkLoginStatusAndToggleStockButtons();
            
            // 先获取配置，然后加载产品数据
            getJadeConfig()
                .then(() => loadAllProducts())
                .catch(error => {
                    console.error('获取配置失败:', error);
                    loadAllProducts(); // 即使配置失败也继续加载产品
                });
            
            // 添加搜索方式改变事件
            document.querySelectorAll('input[name="searchType"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    filterProducts();
                    toggleBuyerSearchPanel();
                });
            });
            
            // 初始显示/隐藏购买人搜索面板
            toggleBuyerSearchPanel();
            
            // 添加类别选择改变事件
            document.getElementById('categorySelect').addEventListener('change', filterProducts);
            
            // 添加输入框实时搜索（防抖）
            let searchTimeout;
            document.getElementById('searchInput').addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(filterProducts, 300);
            });
            
            // 添加排序选择改变事件
            document.getElementById('sortSelect').addEventListener('change', filterProducts);
        });
        
        // 初始化类别选项
        function initCategoryOptions(products) {
            const categorySelect = document.getElementById('categorySelect');
            
            // 清空现有选项（保留"全部"选项）
            while (categorySelect.options.length > 1) {
                categorySelect.remove(1);
            }
            
            // 收集所有 type_1 和 type_2 的值，并建立层级关系
            const categoryMap = new Map();
            
            products.forEach(product => {
                if (product.type_1) {
                    if (!categoryMap.has(product.type_1)) {
                        categoryMap.set(product.type_1, new Set());
                    }
                    if (product.type_2) {
                        categoryMap.get(product.type_1).add(product.type_2);
                    }
                }
            });
            
            // 添加类别选项，type_2 作为 type_1 的子项
            categoryMap.forEach((subCategories, mainCategory) => {
                // 添加主类别
                const mainOption = document.createElement('option');
                mainOption.value = mainCategory;
                mainOption.textContent = mainCategory;
                mainOption.style.fontWeight = 'bold';
                categorySelect.appendChild(mainOption);
                
                // 添加子类别（带缩进）
                subCategories.forEach(subCategory => {
                    const subOption = document.createElement('option');
                    subOption.value = subCategory;
                    subOption.textContent = '  └─ ' + subCategory;
                    categorySelect.appendChild(subOption);
                });
            });
        }

        // 获取所有产品数据
        function loadAllProducts() {
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const container = document.getElementById('productContainer');
            
            loading.style.display = 'block';
            error.style.display = 'none';
            container.innerHTML = '';

            fetch('/get_jade_product_list')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    if (data.res === 'ok' && data.data) {
                        allProducts = data.data; // 保存所有产品数据
                        initCategoryOptions(allProducts); // 初始化类别选项
                        filterProducts(); // 应用当前筛选条件
                    } else {
                        throw new Error('数据格式错误');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载失败: ' + error.message;
                });
        }

        // 筛选产品
        function filterProducts() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const searchType = document.querySelector('input[name="searchType"]:checked').value;
            const category = document.getElementById('categorySelect').value;
            const sortType = document.getElementById('sortSelect').value;
            
            let filteredData = allProducts;
            
            // 类别筛选
            if (category !== 'all') {
                filteredData = filteredData.filter(product => 
                    product.type_1 === category || product.type_2 === category
                );
            }
            
            // 关键词搜索
            if (searchTerm) {
                filteredData = filteredData.filter(product => {
                    const fieldValue = product[searchType];
                    if (!fieldValue) return false;
                    
                    const fieldValueLower = fieldValue.toLowerCase();
                    
                    // 对于五行和颜色搜索，支持多字符匹配（OR逻辑）
                    if (searchType === 'wu_xings' || searchType === 'colors') {
                        // 检查是否包含搜索词中的任意字符或整个搜索词
                        return searchTerm.split('').some(char => fieldValueLower.includes(char)) || 
                               fieldValueLower.includes(searchTerm);
                    } else {
                        // 其他字段使用原来的包含匹配
                        return fieldValueLower.includes(searchTerm);
                    }
                });
            }
            
            // 排序处理
            if (sortType === 'designed_date_desc') {
                // 设计时间降序（最新在前）
                filteredData.sort((a, b) => {
                    const dateA = a.designed_date ? new Date(a.designed_date) : new Date(0);
                    const dateB = b.designed_date ? new Date(b.designed_date) : new Date(0);
                    return dateB - dateA; // 降序
                });
            } else if (sortType === 'designed_date_asc') {
                // 设计时间升序（最旧在前）
                filteredData.sort((a, b) => {
                    const dateA = a.designed_date ? new Date(a.designed_date) : new Date(0);
                    const dateB = b.designed_date ? new Date(b.designed_date) : new Date(0);
                    return dateA - dateB; // 升序
                });
            }
            
            displayProducts(filteredData);
        }
        

        // 显示产品数据
        function displayProducts(products) {
            const container = document.getElementById('productContainer');
            if (products.length === 0) {
                container.innerHTML = '<div class="loading">没有找到匹配的产品</div>';
                return;
            }

            let html = '<div class="product-list">';
            
            products.forEach(product => {
                const imageUrl = getProductImageUrl(product.product_id);
                html += `
                    <div class="product-card">
                        <div class="product-left-column">
                            <img src="${imageUrl}" class="product-image" alt="${product.product_name || '产品图片'}" 
                                 onerror="this.src='/static/images/default_cover.jpg'"
                                 style="cursor: pointer;" onclick="showJadeImages('${product.product_id ? product.product_id.trim() : ''}')">
                            <button class="stock-btn" id="stockBtn_${product.product_id}" onclick="goToStockInput('${product.product_id}', '${product.product_name}')" style="display: none;">
                                <i class="bi bi-box-arrow-in-down"></i> 入库
                            </button>
                            <div class="stock-info" id="stockInfo_${product.product_id}" style="font-size: 12px; color: #888; margin-top: 5px; text-align: center;">
                                当前库存: <span id="stockQty_${product.product_id}">加载中...</span>
                            </div>
                        </div>
                        <div class="product-content">
                            <div class="product-id">${product.product_id || '无编号'}</div>
                            <div class="product-name">${product.product_name || '未命名产品'}</div>
                            <div class="product-material">
                                <strong>主要材质:</strong> ${product.major_material || '未知'}
                            </div>
                            <div class="product-details">
                                <div><strong>颜色:</strong> ${product.colors || '未知'}</div>
                                <div><strong>五行:</strong> ${product.wu_xings || '未知'}</div>
                                <div><strong>直径:</strong> ${product.major_diameter || '未知'} mm</div>
                                <div><strong>总长度:</strong> ${product.total_length || '未知'} cm</div>
                                <div><strong>设计师:</strong> ${product.designer_name || '未知'}</div>
                                <div><strong>设计日期:</strong> ${formatDate(product.designed_date) || '未知'}</div>
                                <div><strong>类型:</strong> ${product.type_1 || ''} ${product.type_2 || ''}</div>
                            </div>
                        </div>
                    </div>
                `;
            });

            html += '</div>';
            container.innerHTML = html;
            
            // 检查登录状态并控制入库按钮显示
            checkLoginStatusAndToggleStockButtons();
            
            // 加载产品库存信息
            loadProductStockInfo(products);
        }

        // 检查登录状态并控制状态栏、入库按钮和返回按钮显示
        function checkLoginStatusAndToggleStockButtons() {
            // 从状态栏获取登录状态 - 检查用户名是否为"未登录"
            const usernameElement = document.querySelector('.username');
            const isLoggedIn = usernameElement && usernameElement.textContent !== '未登录';
            
            // 控制状态栏的显示
            const statusBar = document.querySelector('.status-bar');
            if (statusBar) {
                statusBar.style.display = isLoggedIn ? 'flex' : 'none';
            }
            
            // 控制所有入库按钮的显示
            const stockButtons = document.querySelectorAll('.stock-btn');
            stockButtons.forEach(button => {
                button.style.display = isLoggedIn ? 'block' : 'none';
            });
            
            // 控制返回主菜单按钮的显示
            const backButton = document.querySelector('a[href="/ej_index"]');
            if (backButton) {
                backButton.style.display = isLoggedIn ? 'inline-block' : 'none';
            }
            
            // 调整页面顶部内边距
            if (!isLoggedIn) {
                document.body.style.paddingTop = '0';
            } else {
                document.body.style.paddingTop = '60px';
            }
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN');
            } catch (e) {
                return dateString;
            }
        }

        // 显示/隐藏购买人搜索面板
        function toggleBuyerSearchPanel() {
            const searchType = document.querySelector('input[name="searchType"]:checked').value;
            const buyerSearchPanel = document.getElementById('buyerSearchPanel');
            
            if (searchType === 'buyer') {
                buyerSearchPanel.style.display = 'block';
                document.getElementById('searchInput').style.display = 'none';
                document.querySelector('button[onclick="loadAllProducts()"]').style.display = 'none';
                document.querySelector('.search-controls > div:last-child').style.display = 'none';
            } else {
                buyerSearchPanel.style.display = 'none';
                document.getElementById('searchInput').style.display = 'inline-block';
                document.querySelector('button[onclick="loadAllProducts()"]').style.display = 'inline-block';
                document.querySelector('.search-controls > div:last-child').style.display = 'block';
            }
        }

        // 按购买人搜索
        function searchByBuyer() {
            const buyerName = document.getElementById('buyerNameInput').value.trim();
            if (!buyerName) {
                alert('请输入购买人姓名');
                return;
            }

            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const container = document.getElementById('productContainer');
            
            loading.style.display = 'block';
            error.style.display = 'none';
            container.innerHTML = '';

            fetch(`/search_by_buyer?buyer_name=${encodeURIComponent(buyerName)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success) {
                        if (data.data && data.data.length > 0) {
                            // 先显示产品，然后加载库存信息
                            displayProducts(data.data);
                            // 使用setTimeout确保DOM完全渲染后再加载库存信息
                            setTimeout(() => {
                                loadProductStockInfo(data.data);
                            }, 100);
                        } else {
                            container.innerHTML = `<div class="loading">${data.message || '未找到相关产品'}</div>`;
                        }
                    } else {
                        throw new Error(data.message || '搜索失败');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '搜索失败: ' + error.message;
                });
        }

        // 加载产品库存信息
        function loadProductStockInfo(products) {
            if (!products || products.length === 0) {
                return;
            }
            
            // 提取所有产品ID
            const productIds = products.map(product => product.product_id).filter(id => id);
            
            if (productIds.length === 0) {
                return;
            }
            
            // 调用后端API获取库存信息
            fetch('/get_product_stock_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ product_ids: productIds })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success && data.data) {
                    // 更新每个产品的库存显示
                    updateStockDisplay(data.data);
                } else {
                    throw new Error(data.message || '获取库存信息失败');
                }
            })
            .catch(error => {
                // 如果加载失败，显示错误状态
                updateStockDisplay({});
            });
        }

        // 更新库存显示
        function updateStockDisplay(stockData) {
            // 处理库存数据格式：如果是数组，转换为对象格式
            let processedStockData = {};
            if (Array.isArray(stockData)) {
                stockData.forEach(item => {
                    // 尝试多种可能的字段名组合
                    let productId = item.product_id || item.productId || item.id;
                    let stockQty = item.available_qty !== undefined ? item.available_qty : 
                                  (item.stock_qty !== undefined ? item.stock_qty : 
                                  (item.stock_quantity !== undefined ? item.stock_quantity : 
                                  (item.stockQuantity !== undefined ? item.stockQuantity : 
                                  (item.quantity !== undefined ? item.quantity : 
                                  (item.qty !== undefined ? item.qty : undefined)))));
                    
                    // 确保库存数量是数字类型
                    if (stockQty !== undefined) {
                        stockQty = parseInt(stockQty) || 0;
                    }
                    
                    if (productId && stockQty !== undefined) {
                        processedStockData[productId] = stockQty;
                    }
                });
            } else {
                processedStockData = stockData;
            }
            
            // 遍历所有产品卡片，更新库存显示
            const stockInfoElements = document.querySelectorAll('.stock-info');
            
            stockInfoElements.forEach(element => {
                const productId = element.id.replace('stockInfo_', '');
                const stockQtyElement = document.getElementById(`stockQty_${productId}`);
                
                if (processedStockData[productId] !== undefined) {
                    const stockQty = processedStockData[productId];
                    stockQtyElement.textContent = stockQty;
                    
                    // 根据库存数量设置颜色
                    if (stockQty > 0) {
                        stockQtyElement.style.color = '#28a745'; // 绿色表示有库存
                    } else if (stockQty === 0) {
                        stockQtyElement.style.color = '#dc3545'; // 红色表示无库存
                    } else {
                        stockQtyElement.style.color = '#888'; // 灰色表示未知状态
                    }
                } else {
                    stockQtyElement.textContent = '未知';
                    stockQtyElement.style.color = '#888';
                }
            });
        }

        // 跳转到库存录入页面
        function goToStockInput(productId, productName) {
            // 编码参数
            const encodedId = encodeURIComponent(productId);
            const encodedName = encodeURIComponent(productName);
            
            // 跳转到库存录入页面并传递参数
            window.location.href = `/ej_stock_input?product_id=${encodedId}&product_name=${encodedName}&stock_name=${encodedName}&product_type=玉石产品`;
        }
    </script>
</body>
</html>
